package com.example.mall.filter;

import com.example.mall.constants.BaseConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
public class TokenConverFilter implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {

        //1.获取请求对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if(servletRequestAttributes != null && servletRequestAttributes.getRequest() != null){

            HttpServletRequest request = servletRequestAttributes.getRequest();

            //2.从请求头获取到令牌
            String authorization = request.getHeader(BaseConstants.Uaa.AUTHORIZATION_HEADER);
            if(StringUtils.hasLength(authorization)){
                log.info("TOKEN转发 => {}",authorization);
                //3.把令牌添加到Fiegn的请求头
                requestTemplate.header(BaseConstants.Uaa.AUTHORIZATION_HEADER,authorization);
            }else{
                log.warn("TOKEN转发 => 请求头无Token");
            }
        }else{
            log.error("TOKEN转发 => 请求对象为空");
        }
    }
}
